package com.opennice.soukaoti.indexImpl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import net.paoding.analysis.analyzer.PaodingAnalyzer;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.Scorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.opennice.soukaoti.index.IndexUtilInterface;
import com.opennice.soukaoti.index.KaoTiIndexBean;
import com.opennice.soukaoti.index.util.IndexTools;

public class IndexUtilImpl implements IndexUtilInterface {

    File dataFile = new File("D://indexFile");
    Analyzer analyzer = new PaodingAnalyzer();
    /**
     * Field.Index.NO 表示不索引
     * Field.Index.ANALYZED 表示分词且索引
     * Field.Index.NOT_ANALYZED 表示不分词且索引
     */
    
    
	@Override
	public void addDocument(KaoTiIndexBean kaoTiIndexBean) {
		// TODO Auto-generated method stub
		    Directory directory = null;
	        IndexWriter writer = null;
	        try {
	            directory = FSDirectory.open(dataFile);
	            IndexWriterConfig writerConfig = new IndexWriterConfig(Version.LUCENE_32, analyzer);
	            writer = new IndexWriter(directory, writerConfig);
	            Document doc = new Document();
	            
	        	doc.add(new Field("PId", kaoTiIndexBean.getPId().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
	        	doc.add(new Field("PName", kaoTiIndexBean.getPName(), Field.Store.YES, Field.Index.ANALYZED));
	        	doc.add(new Field("PExaminationTime", kaoTiIndexBean.getPExaminationTime().toGMTString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
	        	doc.add(new Field("PAuthor", kaoTiIndexBean.getPAuthor(), Field.Store.YES, Field.Index.ANALYZED));
	        	
	        	doc.add(new Field("pfId", kaoTiIndexBean.getPfId().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
	        	doc.add(new Field("pfName", kaoTiIndexBean.getPfName(), Field.Store.YES, Field.Index.ANALYZED));
	        	
	        	doc.add(new Field("ptId", kaoTiIndexBean.getPtId().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
	        	doc.add(new Field("ptName", kaoTiIndexBean.getPtName(), Field.Store.YES, Field.Index.ANALYZED));
                doc.add(new Field("ptMark", kaoTiIndexBean.getPtMark().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("ptKind", kaoTiIndexBean.getPtKind().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("ptState", kaoTiIndexBean.getPtState().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                
                doc.add(new Field("paAnswer", kaoTiIndexBean.getPaAnswer(), Field.Store.YES, Field.Index.ANALYZED));
                doc.add(new Field("paId", kaoTiIndexBean.getPaId(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                
                writer.addDocument(doc);
                writer.optimize();
                writer.close();
	        }catch(Exception ex){
	            ex.printStackTrace();
	        }
	}
	@Override
	public void deleteDocument(String ptId) {
		// TODO Auto-generated method stub
		 try {
	            Directory directory = FSDirectory.open(dataFile);
	            IndexWriterConfig writerConfig = new IndexWriterConfig(Version.LUCENE_32, analyzer);
	            IndexWriter writer = new IndexWriter(directory, writerConfig);
	            Term term = new Term("ptId", ptId);
	            writer.deleteDocuments(term);  
	            writer.optimize();
	            writer.close();
	            directory.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	}
	
	public ArrayList<KaoTiIndexBean> searchQuery(String queryStrs, int firstResult, int maxReuslt,String field) {
		IndexSearcher isearcher = null;
        Directory directory = null;
        ArrayList<KaoTiIndexBean> result=new ArrayList<KaoTiIndexBean>();
        try {
            directory = FSDirectory.open(dataFile);
            isearcher = new IndexSearcher(directory,true);
            QueryParser parser = new QueryParser(Version.LUCENE_32, field, analyzer);
            Query query = parser.parse(queryStrs);
            TopDocs topDocs = isearcher.search(query,100);
            ScoreDoc[] hits = topDocs.scoreDocs;
            Formatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
            Scorer scorer = new QueryScorer(query);
            Highlighter highlighter = new Highlighter(formatter, scorer);
 
            Fragmenter fragmenter = new SimpleFragmenter(100);
            highlighter.setTextFragmenter(fragmenter);
            for(ScoreDoc scoreDoc : hits){
                Document hitDoc = isearcher.doc(scoreDoc.doc);
                KaoTiIndexBean kaoTiIndexBean=new KaoTiIndexBean();
                kaoTiIndexBean.setPId(Integer.valueOf(hitDoc.get("PId")));
                kaoTiIndexBean.setPName(hitDoc.get("PName"));
                kaoTiIndexBean.setPExaminationTime(new Date(hitDoc.get("PExaminationTime")));
                kaoTiIndexBean.setPaAnswer(hitDoc.get("PAuthor"));
                kaoTiIndexBean.setPfId(Integer.valueOf(hitDoc.get("pfId")));
                kaoTiIndexBean.setPfName(hitDoc.get("pfName"));
                kaoTiIndexBean.setPtId(Integer.valueOf(hitDoc.get("ptId")));
                kaoTiIndexBean.setPtName(hitDoc.get("ptName"));
                kaoTiIndexBean.setPtMark(Double.valueOf(hitDoc.get("ptMark")));
                kaoTiIndexBean.setPtKind(Integer.valueOf(hitDoc.get("ptKind")));
                kaoTiIndexBean.setPtState(Integer.valueOf(hitDoc.get("ptState")));
                kaoTiIndexBean.setPaAnswer(hitDoc.get("paAnswer"));
                kaoTiIndexBean.setPaId(hitDoc.get("paId"));
                String content = highlighter.getBestFragment(analyzer, "PAuthor", hitDoc.get("PAuthor"));
                result.add(kaoTiIndexBean);
            }
            
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                isearcher.close();
                directory.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		return result;
	}

	@Override
	public void updateDocument(KaoTiIndexBean kaoTiIndexBean) {
		// TODO Auto-generated method stub
        try {          
            Directory directory = FSDirectory.open(dataFile);
            IndexWriterConfig writerConfig = new IndexWriterConfig(Version.LUCENE_32, analyzer);
            IndexWriter writer = new IndexWriter(directory, writerConfig);
            Document doc = new Document();
            
        	doc.add(new Field("PId", kaoTiIndexBean.getPId().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
        	doc.add(new Field("PName", kaoTiIndexBean.getPName(), Field.Store.YES, Field.Index.ANALYZED));
        	doc.add(new Field("PExaminationTime", kaoTiIndexBean.getPExaminationTime().toGMTString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
        	doc.add(new Field("PAuthor", kaoTiIndexBean.getPAuthor(), Field.Store.YES, Field.Index.ANALYZED));
        	
        	doc.add(new Field("pfId", kaoTiIndexBean.getPfId().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
        	doc.add(new Field("pfName", kaoTiIndexBean.getPfName(), Field.Store.YES, Field.Index.ANALYZED));
        	
        	doc.add(new Field("ptId", kaoTiIndexBean.getPtId().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
        	doc.add(new Field("ptName", kaoTiIndexBean.getPtName(), Field.Store.YES, Field.Index.ANALYZED));
            doc.add(new Field("ptMark", kaoTiIndexBean.getPtMark().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.add(new Field("ptKind", kaoTiIndexBean.getPtKind().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.add(new Field("ptState", kaoTiIndexBean.getPtState().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            
            doc.add(new Field("paAnswer", kaoTiIndexBean.getPaAnswer(), Field.Store.YES, Field.Index.ANALYZED));
            doc.add(new Field("paId", kaoTiIndexBean.getPaId(), Field.Store.YES, Field.Index.NOT_ANALYZED));
             
            Term term = new Term("ptId", kaoTiIndexBean.getPtId().toString());
             
            writer.updateDocument(term, doc);
            writer.optimize();
            writer.close();
            directory.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

	}
	
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 KaoTiIndexBean kaoTiIndexBean=new KaoTiIndexBean();
         kaoTiIndexBean.setPId(1);
         
         kaoTiIndexBean.setPName("PName");
         kaoTiIndexBean.setPExaminationTime(new Date(System.currentTimeMillis()));
         kaoTiIndexBean.setPAuthor("PAuthor");
         kaoTiIndexBean.setPfId(2);
         kaoTiIndexBean.setPfName("pfName");
         kaoTiIndexBean.setPtId(7);
         kaoTiIndexBean.setPtName("ptName");
         kaoTiIndexBean.setPtMark(1.323);
         kaoTiIndexBean.setPtKind(3);
         kaoTiIndexBean.setPtState(4);
         kaoTiIndexBean.setPaAnswer("paAnswer");
         kaoTiIndexBean.setPaId("1");
         IndexUtilImpl service=new IndexUtilImpl();
         service.addDocument(kaoTiIndexBean);
         IndexTools.getDoucmentSum();
         
         service.deleteDocument("7");
         
         kaoTiIndexBean.setPName("liulxiang");
         service.updateDocument(kaoTiIndexBean);
         IndexTools.getDoucmentSum();
         ArrayList<KaoTiIndexBean> result=service.searchQueryAsptName("ptName", 1, 2);
         System.out.println(result.size());
         for(KaoTiIndexBean kao:result){
        	 System.out.println(kao.getPaAnswer());
        	 System.out.println(kao.getPName());
        	 System.out.println(kao.getPtId());
        	 System.out.println(kao.getPtName());
         }

	}

	@Override
	public ArrayList<KaoTiIndexBean> searchQueryAsPAuthor(String queryStrs,
			int firstResult, int maxReuslt) {
		IndexSearcher isearcher = null;
        Directory directory = null;
        ArrayList<KaoTiIndexBean> result=new ArrayList<KaoTiIndexBean>();
        try {
            directory = FSDirectory.open(dataFile);
            isearcher = new IndexSearcher(directory,true);
            QueryParser parser = new QueryParser(Version.LUCENE_32, "PAuthor", analyzer);
            Query query = parser.parse(queryStrs);
            TopDocs topDocs = isearcher.search(query,100);
            ScoreDoc[] hits = topDocs.scoreDocs;
            Formatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
            Scorer scorer = new QueryScorer(query);
            Highlighter highlighter = new Highlighter(formatter, scorer);
 
            Fragmenter fragmenter = new SimpleFragmenter(100);
            highlighter.setTextFragmenter(fragmenter);
            for(ScoreDoc scoreDoc : hits){
                Document hitDoc = isearcher.doc(scoreDoc.doc);
                KaoTiIndexBean kaoTiIndexBean=new KaoTiIndexBean();
                kaoTiIndexBean.setPId(Integer.valueOf(hitDoc.get("PId")));
                kaoTiIndexBean.setPName(hitDoc.get("PName"));
                kaoTiIndexBean.setPExaminationTime(new Date(hitDoc.get("PExaminationTime")));
                kaoTiIndexBean.setPaAnswer(hitDoc.get("PAuthor"));
                kaoTiIndexBean.setPfId(Integer.valueOf(hitDoc.get("pfId")));
                kaoTiIndexBean.setPfName(hitDoc.get("pfName"));
                kaoTiIndexBean.setPtId(Integer.valueOf(hitDoc.get("ptId")));
                kaoTiIndexBean.setPtName(hitDoc.get("ptName"));
                kaoTiIndexBean.setPtMark(Double.valueOf(hitDoc.get("ptMark")));
                kaoTiIndexBean.setPtKind(Integer.valueOf(hitDoc.get("ptKind")));
                kaoTiIndexBean.setPtState(Integer.valueOf(hitDoc.get("ptState")));
                kaoTiIndexBean.setPaAnswer(hitDoc.get("paAnswer"));
                kaoTiIndexBean.setPaId(hitDoc.get("paId"));
                String content = highlighter.getBestFragment(analyzer, "PAuthor", hitDoc.get("PAuthor"));
            }
             
             
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                isearcher.close();
                directory.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		return null;
	}

	@Override
	public ArrayList<KaoTiIndexBean> searchQueryAsPExaminationTime(
			String queryStrs, int firstResult, int maxReuslt) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ArrayList<KaoTiIndexBean> searchQueryAsPName(String queryStrs,
			int firstResult, int maxReuslt) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ArrayList<KaoTiIndexBean> searchQueryAspaAnswer(String queryStrs,
			int firstResult, int maxReuslt) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ArrayList<KaoTiIndexBean> searchQueryAspfName(String queryStrs,
			int firstResult, int maxReuslt) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ArrayList<KaoTiIndexBean> searchQueryAsptName(String queryStrs,
			int firstResult, int maxReuslt) {
		IndexSearcher isearcher = null;
        Directory directory = null;
        ArrayList<KaoTiIndexBean> result=new ArrayList<KaoTiIndexBean>();
        try {
            directory = FSDirectory.open(dataFile);
            isearcher = new IndexSearcher(directory,true);
            QueryParser parser = new QueryParser(Version.LUCENE_32, "ptName", analyzer);
            Query query = parser.parse(queryStrs);
            TopDocs topDocs = isearcher.search(query,100);
            ScoreDoc[] hits = topDocs.scoreDocs;
            Formatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
            Scorer scorer = new QueryScorer(query);
            Highlighter highlighter = new Highlighter(formatter, scorer);
 
            Fragmenter fragmenter = new SimpleFragmenter(100);
            highlighter.setTextFragmenter(fragmenter);
            for(ScoreDoc scoreDoc : hits){
                Document hitDoc = isearcher.doc(scoreDoc.doc);
                KaoTiIndexBean kaoTiIndexBean=new KaoTiIndexBean();
                kaoTiIndexBean.setPId(Integer.valueOf(hitDoc.get("PId")));
                kaoTiIndexBean.setPName(hitDoc.get("PName"));
                kaoTiIndexBean.setPExaminationTime(new Date(hitDoc.get("PExaminationTime")));
                kaoTiIndexBean.setPaAnswer(hitDoc.get("PAuthor"));
                kaoTiIndexBean.setPfId(Integer.valueOf(hitDoc.get("pfId")));
                kaoTiIndexBean.setPfName(hitDoc.get("pfName"));
                kaoTiIndexBean.setPtId(Integer.valueOf(hitDoc.get("ptId")));
                kaoTiIndexBean.setPtName(hitDoc.get("ptName"));
                kaoTiIndexBean.setPtMark(Double.valueOf(hitDoc.get("ptMark")));
                kaoTiIndexBean.setPtKind(Integer.valueOf(hitDoc.get("ptKind")));
                kaoTiIndexBean.setPtState(Integer.valueOf(hitDoc.get("ptState")));
                kaoTiIndexBean.setPaAnswer(hitDoc.get("paAnswer"));
                kaoTiIndexBean.setPaId(hitDoc.get("paId"));
                
                
                String ptName = highlighter.getBestFragment(analyzer, "ptName", hitDoc.get("ptName"));
                kaoTiIndexBean.setPtName(ptName);
                result.add(kaoTiIndexBean);
            }
            
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
		return result;
	}

}
